/**
 * PLM 项目Store
 * 使用统一配置入口模式
 */

// 引入依赖
const pathResolver = require('../config/path_resolver.js');

// 从配置文件导入服务
const services = require('../config/services_config.js');
const { resourceService, projectService, flowService, researchService } = services;

// 从配置文件导入工具助手
let helpers = {
  cacheHelper: {
    get: (key, def = null) => def,
    set: () => {},
    remove: () => {},
    clear: () => {}
  },
  timeHelper: {
    formatDate: () => new Date().toISOString(),
    getNow: () => new Date().toISOString(),
    getTimeID: () => Date.now().toString()
  }
};

// 尝试导入工具助手配置
try {
  helpers = require('../config/simple_helpers_config.js');
} catch (e) {
  console.warn('导入工具助手配置失败，使用默认实现', e);
}

const cacheHelper = helpers.cacheHelper;
const timeHelper = helpers.timeHelper;

// 尝试导入mobx
let mobx = {
  observable: (obj) => obj,
  runInAction: (fn) => fn()
};

try {
  mobx = require('mobx-miniprogram');
} catch (e) {
  console.warn('导入mobx-miniprogram失败，使用简化实现', e);
}

// 创建Store
const createStore = () => {
  return mobx.observable({
    // 状态数据
    data: {
      isLoading: false,
      projects: [],
      currentProject: null,
      notifications: [],
      filterOptions: {
        status: 'all',
        searchText: ''
      }
    },
    
    // 计算属性
    get filteredProjects() {
      const { projects, filterOptions } = this.data;
      
      return projects.filter(project => {
        // 状态过滤
        if (filterOptions.status !== 'all' && 
            project.status.toString() !== filterOptions.status) {
          return false;
        }
        
        // 关键词过滤
        if (filterOptions.searchText && 
            !project.name.includes(filterOptions.searchText)) {
          return false;
        }
        
        return true;
      });
    },
    
    // 行为方法
    actions: {
      // 加载项目列表
      async loadProjects() {
        let PlmService;
        try {
          // 使用正确的服务配置
          PlmService = services.projectService || services.plmMockService;
        } catch (e) {
          console.warn('加载 PlmService 失败，使用模拟数据', e);
          // 提供模拟服务
          PlmService = {
            getQuickAccessProjects: async () => {
              return [
                { id: 'p001', name: '模拟项目1', status: 1, createTime: Date.now() },
                { id: 'p002', name: '模拟项目2', status: 2, createTime: Date.now() }
              ];
            },
            formatProjectForDisplay: (p) => p
          };
        }
        
        this.data.isLoading = true;
        
        try {
          const projects = await PlmService.getQuickAccessProjects();
          // 格式化数据
          const formattedProjects = projects.map(p => PlmService.formatProjectForDisplay(p));
          
          mobx.runInAction(() => {
            this.data.projects = formattedProjects;
            this.data.isLoading = false;
          });
        } catch (error) {
          console.error('加载项目列表失败', error);
          mobx.runInAction(() => {
            this.data.isLoading = false;
          });
        }
      },
      
      // 设置筛选选项
      setFilter(options) {
        mobx.runInAction(() => {
          this.data.filterOptions = {
            ...this.data.filterOptions,
            ...options
          };
        });
      },
      
      // 加载项目详情
      async loadProjectDetail(id) {
        if (!id) return;
        
        this.data.isLoading = true;
        
        try {
          // 使用导入的服务
          let PlmService = services.projectService || services.plmMockService;
          
          const project = await PlmService.getProjectDetail(id);
          const formatted = PlmService.formatProjectForDisplay(project);
          
          mobx.runInAction(() => {
            this.data.currentProject = formatted;
            this.data.isLoading = false;
          });
        } catch (error) {
          console.error('加载项目详情失败', error);
          mobx.runInAction(() => {
            this.data.isLoading = false;
          });
        }
      },
      
      // 清除缓存
      clear() {
        mobx.runInAction(() => {
          this.data.projects = [];
          this.data.currentProject = null;
          this.data.notifications = [];
          this.data.isLoading = false;
        });
      }
    }
  });
};

// 创建并导出Store
const plmStore = createStore();
module.exports = plmStore; 